package com.soundai.skill.helloworld.handlers;

import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.dispatcher.request.handler.impl.CanFulfillIntentRequestHandler;
import com.amazon.ask.model.Response;
import com.amazon.ask.model.Slot;
import com.amazon.ask.model.canfulfill.*;
import com.soundai.skill.helloworld.HttpHelper.HttpClientHelper;
import com.soundai.skill.helloworld.Service.AIService;
import com.soundai.skill.helloworld.Service.ShoppingService;
import com.soundai.skill.helloworld.Service.WisdomHomeService;
import com.soundai.skill.helloworld.baiduApi.AipNlpClass;
import com.soundai.skill.helloworld.baiduApi.ApiNlpDataHelper;
import com.soundai.skill.helloworld.config.uriConfig;
import com.soundai.skill.helloworld.helper.Base64Util;
import com.soundai.skill.helloworld.helper.TextConvertNumber;
import com.soundai.skill.helloworld.helper.Utils;
import com.soundai.skill.helloworld.log.logC;
import com.soundai.skill.helloworld.socket.SocketClient;
import com.soundai.skill.helloworld.time.DateUtil;
import com.soundai.skill.helloworld.time.TimeNormalizer;
import com.soundai.skill.helloworld.time.TimeUnit;
import com.sun.javafx.collections.MappingChange;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.json.JSONException;
import redis.clients.jedis.Jedis;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

import static com.amazon.ask.request.Predicates.canFulfillIntentName;
import static com.amazon.ask.request.Predicates.intentName;

public class CommonHandler implements CanFulfillIntentRequestHandler {
    @Override
    public boolean canHandle(HandlerInput handlerInput, CanFulfillIntentRequest canFulfillIntentRequest) {
        logC.writeFile("",handlerInput.getRequestEnvelope().getContext().getSystem().getDevice().getDeviceId()+"开始CanFulfillIntentRequest时间："+logC.getCurrentYYYYMMDDHHMMSS()+"\r\n");
        logC.writeFile("","canFulfill:"+handlerInput.toString()+"****请求内容:"+canFulfillIntentRequest.toString()+"\r\n");

        String requestIntentName = canFulfillIntentRequest.getIntent().getName();
        ///判断是否存在技能 （false：不存在,true：存在）
        boolean istrue =  handlerInput.matches(canFulfillIntentName(requestIntentName));
        return istrue;
    }



    /**
     * 隐式调用（Name-free Interaction）回传音箱
     * @param handlerInput
     * @param canFulfillIntentRequest
     * @return
     */
    @Override
    public Optional<Response> handle(HandlerInput handlerInput, CanFulfillIntentRequest canFulfillIntentRequest) {
        CanFulfillSlot CanUnderstand ;
        CanFulfillIntent canFulfillIntent=null;
       try {
           Slot slot = canFulfillIntentRequest.getIntent().getSlots().get("SlotName");
           String v = slot.getValue();
           JSONObject objV = JSONObject.fromObject(v);
           String answer="";
           if (objV.get("answer")!=null)
               answer = objV.get("answer").toString();
           String domainArea = canFulfillIntentRequest.getIntent().getName();
           String speekstr = objV.get("query").toString().trim();
           ///蓝牙特殊处理
           if (speekstr.indexOf("打开蓝牙")>-1||speekstr.indexOf("关闭蓝牙")>-1)
           {
               CanUnderstand = CanFulfillSlot.builder().withCanUnderstand(CanUnderstandSlotValues.NO).withCanFulfill(CanFulfillSlotValues.NO).build();
               canFulfillIntent = CanFulfillIntent.builder().withCanFulfill(CanFulfillIntentValues.NO).putSlotsItem("slotName1", CanUnderstand).build();
               return handlerInput.getResponseBuilder().withCanFulfillIntent(canFulfillIntent).build();
           }
           JSONObject speek=new JSONObject();
           speek.put("query",speekstr);
           speek.put("realm",domainArea);

           //SocketClient.sendtts("0760c53ba14374872777f3c1529f389f","欢迎光临智慧体验屋");
           URL url = TimeNormalizer.class.getResource("/TimeExp.m");
           System.out.println(url.toURI().toString());
           TimeNormalizer normalizer = new TimeNormalizer(url.toURI().toString());
           normalizer.setPreferFuture(true);
           normalizer.parse(objV.get("query").toString().trim());
           TimeUnit[] unit = normalizer.getTimeUnit();

           if (unit.length>0)
               speek.put("fromtime", ""+unit[0].getTime().getTime());

           if (unit.length>1)
               speek.put("lasttime",""+unit[1].getTime().getTime());


           JSONObject returnMsg = WisdomHomeService.requestSound(handlerInput, speek.toString());
           canFulfillIntent = WisdomHomeService.responeCanFulfillSlot(returnMsg, speek.toString(),domainArea,answer,handlerInput);

           logC.writeFile("","结束CanFulfillIntentRequest时间："+logC.getCurrentYYYYMMDDHHMMSS()+"\r\n");
           //判断返回结果，并根据音响回传协议进行设置返回值
          //CanFulfillIntent canFulfillIntent = WisdomHomeService.responeCanFulfillSlot(returnMsg, speek,area,handlerInput);
           return handlerInput.getResponseBuilder()
                   .withCanFulfillIntent(canFulfillIntent).build();
       }catch (Exception ex){
           logC.writeFile("",ex.toString());
           CanUnderstand = CanFulfillSlot.builder().withCanUnderstand(CanUnderstandSlotValues.NO).withCanFulfill(CanFulfillSlotValues.NO).build();
           canFulfillIntent = CanFulfillIntent.builder().withCanFulfill(CanFulfillIntentValues.NO).putSlotsItem("slotName1", CanUnderstand).build();
       }
        return handlerInput.getResponseBuilder()
               .build();
    }







}
